package com.albert.HttpUtils;

import android.os.Handler;
import android.os.Looper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public interface HttpCallback {
        void onSuccess(String response);
        void onFailure(Exception e);
    }

    private static final int TIMEOUT = 10000; // 10秒超时

    /**
     * GET 请求
     */
    public static void get(final String urlStr, final HttpCallback callback) {
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urlStr);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(TIMEOUT);
                connection.setReadTimeout(TIMEOUT);

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                    );
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    postSuccess(callback, response.toString());
                } else {
                    postFailure(callback, new Exception("HTTP error code: " + responseCode));
                }
            } catch (Exception e) {
                postFailure(callback, e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();
    }

    /**
     * POST 请求
     */
    public static void post(final String urlStr, final String params, final HttpCallback callback) {
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urlStr);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(TIMEOUT);
                connection.setReadTimeout(TIMEOUT);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

                // 如果 params 不为空才写入输出流
                if (params != null && !params.isEmpty()) {
                    OutputStream os = connection.getOutputStream();
                    os.write(params.getBytes("UTF-8"));
                    os.flush();
                    os.close();
                }

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                    );
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    postSuccess(callback, response.toString());
                } else {
                    postFailure(callback, new Exception("HTTP error code: " + responseCode));
                }
            } catch (Exception e) {
                postFailure(callback, e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();
    }

    /**
     * 在主线程回调成功
     */
    private static void postSuccess(final HttpCallback callback, final String response) {
        new Handler(Looper.getMainLooper()).post(() -> callback.onSuccess(response));
    }

    /**
     * 在主线程回调失败
     */
    private static void postFailure(final HttpCallback callback, final Exception e) {
        new Handler(Looper.getMainLooper()).post(() -> callback.onFailure(e));
    }
}
